<template>
  <div class="course-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left-buttons">
        <el-button type="primary" @click="dialogFormVisible = true">
          <el-icon><Plus /></el-icon>添加
        </el-button>
        <el-button type="danger" @click="deleteTick">
          <el-icon><Delete /></el-icon>勾选删除
        </el-button>
      </div>
      <div class="search-box">
        <el-input
          v-model="searchAll"
          placeholder="请输入课程类型名称搜索"
          clearable
          @keyup.enter="serchBtn"
        />
        <el-button type="primary" @click="serchBtn">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button @click="resetSerchbtn">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="courseData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="courseTypeId" label="类型编号" width="100" />
      <el-table-column prop="courseTypeName" label="类型名称" />
      <el-table-column prop="courseTypeIcon" label="类型图标">
        <template #default="scope">
          <el-image
            v-if="scope.row.courseTypeIcon"
            :src="scope.row.courseTypeIcon"
            style="width: 50px; height: 50px"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="parentTypeId" label="父类型编号" width="120" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.courseTypeId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <div class="pagination-wrapper">
        <span class="total-text">Total {{ total }}</span>
        <el-select v-model="pageSize" class="page-size-select" popper-class="page-size-dropdown">
          <el-option label="5/page" :value="5" />
          <el-option label="10/page" :value="10" />
          <el-option label="20/page" :value="20" />
        </el-select>
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          class="custom-pagination"
        />
        <div class="goto-wrapper">
          <span class="goto-text">Go to</span>
          <el-input
            v-model="currentPage"
            class="goto-input"
            type="number"
            min="1"
            :max="Math.ceil(total / pageSize)"
          />
        </div>
      </div>
    </div>

    <!-- 添加对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="添加课程类型"
      width="500px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="类型名称" required>
          <el-input v-model="form.courseTypeName" />
        </el-form-item>
        <el-form-item label="类型图标">
          <el-input v-model="form.courseTypeIcon" />
        </el-form-item>
        <el-form-item label="父类型编号">
          <el-input v-model="form.parentTypeId" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改课程类型"
      width="500px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="类型名称" required>
          <el-input v-model="editForm.courseTypeName" />
        </el-form-item>
        <el-form-item label="类型图标">
          <el-input v-model="editForm.courseTypeIcon" />
        </el-form-item>
        <el-form-item label="父类型编号">
          <el-input v-model="editForm.parentTypeId" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

// 基础数据
const loading = ref(false)
const courseData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const searchAll = ref('')
const dialogFormVisible = ref(false)
const editDialogVisible = ref(false)

// 表单数据
const form = ref({
  courseTypeName: '',
  courseTypeIcon: '',
  parentTypeId: null
})

// 编辑表单数据
const editForm = ref({
  courseTypeId: '',
  courseTypeName: '',
  courseTypeIcon: '',
  parentTypeId: null
})

// 获取课程列表数据
const getcoursesList = async () => {
  loading.value = true
  try {
    const response = await axios.get('admin/courseTypes/search', {
      params: {
        keyword: searchAll.value,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      courseData.value = response.data.data.list
      total.value = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 添加课程类型
const handleAdd = async () => {
  try {
    const response = await axios.post('admin/courseTypes', form.value)
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogFormVisible.value = false
      getcoursesList()
      form.value = { courseTypeName: '', courseTypeIcon: '', parentTypeId: null }
    } else {
      ElMessage.error(response.data.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

// 删除课程类型
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程类型吗？', '提示', {
      type: 'warning'
    })
    const response = await axios.delete(`admin/courseTypes/delete/${id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getcoursesList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败')
  }
}

// 修改课程类型
const handleEdit = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

const submitEdit = async () => {
  try {
    const response = await axios.put(`admin/courseTypes/update/${editForm.value.courseTypeId}`, editForm.value)
    if (response.data.code === 200) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      getcoursesList()
    } else {
      ElMessage.error(response.data.msg || '修改失败')
    }
  } catch (error) {
    ElMessage.error('修改失败')
  }
}

// 批量删除
const selectedRows = ref([])
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const deleteTick = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的课程类型')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的课程类型吗？', '提示', {
      type: 'warning'
    })
    
    // 直接获取选中行的ID数组
    const ids = selectedRows.value.map(item => item.courseTypeId)
    
    // 发送请求，直接传递ID数组
    const response = await axios({
      method: 'DELETE',
      url: 'admin/courseTypes/batch',
      headers: {
        'Content-Type': 'application/json'
      },
      data: ids  // 直接发送ID数组，不需要包装对象
    })

    if (response.data.code === 200) {
      ElMessage.success('批量删除成功')
      selectedRows.value = [] // 清空选中项
      await getcoursesList() // 刷新列表
    } else {
      throw new Error(response.data.msg || '批量删除失败')
    }
  } catch (error) {
    console.error('批量删除错误:', error)
    ElMessage.error(error.message || '批量删除失败')
  }
}

// 搜索功能
const serchBtn = () => {
  currentPage.value = 1
  getcoursesList()
}

// 重置搜索
const resetSerchbtn = () => {
  searchAll.value = ''
  currentPage.value = 1
  getcoursesList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getcoursesList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getcoursesList()
}

onMounted(() => {
  getcoursesList()
})
</script>

<style scoped>
.course-container {
  padding: 20px;
  background-color: #ededed;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 10px;
  padding: 5px 0;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 12px;
  height: 32px;
}

.total-text {
  color: #606266;
  font-size: 13px;
}

.page-size-select {
  width: 120px;
  :deep(.el-input__wrapper) {
    height: 28px;
    line-height: 28px;
    //padding: 0 3px 0 3px;
  }
  :deep(.el-input__inner) {
    font-size: 13px;
  }
  :deep(.el-input__suffix) {
    right: 2px;
  }
}

.goto-wrapper {
  display: flex;
  align-items: center;
  gap: 6px;
  height: 32px;
}

.goto-text {
  color: #606266;
  font-size: 13px;
}

.goto-input {
  width: 50px;
  :deep(.el-input__wrapper) {
    padding: 0 4px;
    height: 28px;
    line-height: 28px;
  }
  :deep(.el-input__inner) {
    height: 28px;
    line-height: 28px;
    text-align: center;
  }
}

:deep(.el-pagination) {
  margin: 0;
  padding: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

.custom-pagination {
  margin: 0;
  :deep(.el-pagination__total),
  :deep(.el-pagination__jump) {
    line-height: 32px;
  }
  
  :deep(.el-pager) {
    margin: 0;
    padding: 0;
    display: flex;
    align-items: center;
  }

  :deep(.el-pager li) {
    margin: 0 4px;
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    vertical-align: middle;
  }

  :deep(.btn-prev),
  :deep(.btn-next) {
    height: 28px;
    line-height: 28px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

:deep(.el-select-dropdown.page-size-dropdown) {
  min-width: 60px !important;
}

:deep(.el-select-dropdown__item) {
  padding: 0 6px;
  font-size: 13px;
}
</style>